<!--
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-02 09:54:41
 * @LastEditTime : 2023-12-07 10:42:11
-->
<script lang="ts" setup name="Tools">
import { useI18n } from 'vue-i18n'
import { useFullscreen } from '@vueuse/core'
import useSettingsStore from '@g/store/modules/settings'
import useUserStore from '@g/store/modules/user'
import useNotificationStore from '@g/store/modules/notification'
import { ElMessage, ElPopover } from 'element-plus'
import { ikMitt, ikStore } from 'iking-utils'

import Notification from './Notification/index.vue'
import { systemConfig } from '@/system.config'

const tools = systemConfig.tools
const router = useRouter()

const settingsStore = useSettingsStore()
const userStore = useUserStore()
const notifucationStore = useNotificationStore()
const { setFileUrl } = useHttpUrl()
notifucationStore.init()

const { t } = useI18n()

const generateI18nTitle = inject(InjectionI18nTitle) as Function

const mainPage = useMainPage()
const { isFullscreen, toggle } = useFullscreen()

function userCommand(command: 'home' | 'setting' | 'hotkeys' | 'logout' | 'password') {
  switch (command) {
    case 'home':
      router.push({
        name: 'home'
      })
      break
    case 'password':
      userStore.updatePwdVisible(true, 'update')
      break
    case 'setting':
      router.push({
        name: 'personalSetting'
      })
      break
    case 'hotkeys':
      ikMitt.emit('global-hotkeys-intro-toggle')
      break
    case 'logout':
      ElMessage.info(t('app.logout'))
      userStore.logout().then(() => {
        router.push({
          name: 'login'
        })
      })
      break
  }
}

const iconSize = 20
const changeTenant = () => {
  userStore.showTenant = true
  router.push({
    name: 'login'
  })
}

function toggleColorScheme(event: MouseEvent) {
  const { startViewTransition } = useViewTransition(() => {
    settingsStore.setColorScheme(settingsStore.settings.app.colorScheme === 'dark' ? 'light' : 'dark')
  })
  startViewTransition().ready.then(() => {
    const x = event.clientX
    const y = event.clientY
    const endRadius = Math.hypot(
      Math.max(x, innerWidth - x),
      Math.max(y, innerHeight - y)
    )
    const clipPath = [
      `circle(0px at ${x}px ${y}px)`,
      `circle(${endRadius}px at ${x}px ${y}px)`
    ]
    document.documentElement.animate(
      {
        clipPath: settingsStore.settings.app.colorScheme !== 'dark' ? clipPath : clipPath.reverse()
      },
      {
        duration: 300,
        easing: 'ease-out',
        pseudoElement: settingsStore.settings.app.colorScheme !== 'dark' ? '::view-transition-new(root)' : '::view-transition-old(root)'
      }
    )
  })
}

const isLight = computed(() => settingsStore.settings.app.colorScheme === 'light')

const refNews: Ref<{ hide: Function; } | null> = ref(null)
const handClosePopover = () => {
  refNews.value?.hide()
}

const showOrgPicker = ref(false)
const changeOrg = () => {
  showOrgPicker.value = !showOrgPicker.value
}
const selectOrg = ref(userStore.organiza.select)
const orgizaList = computed(() => userStore.organiza.list)
const handChangeOrg = (val: string) => {
  userStore.organiza.select = val
  ikStore.local.setItem(ELocal.ORGANIZA, {
    select: val,
    list: orgizaList.value
  })
}
</script>

<template>
  <div class="tools">
    <el-select
      v-model="selectOrg"
      class="nav-org-picker"
      :class="{ show: showOrgPicker } "
      filterable
      @change="handChangeOrg"
    >
      <el-option
        v-for="item in orgizaList"
        :key="item.orgId"
        :label="item.orgName"
        :value="item.orgId"
      />
    </el-select>
    <div class="buttons">
      <span v-if="tools?.org" class="item item-switch">
        <IkSvgIcon
          :size="iconSize"
          pop
          :type="showOrgPicker ? 'primary' : ''"
          :title="showOrgPicker ? '收起切换组织' : '切换组织'"
          name="iksvg_bumenguanli"
          @click="changeOrg"
        />
      </span>
      <span v-if="tools?.tenant" class="item item-switch" @click="changeTenant">
        <IkSvgIcon
          :size="iconSize"
          pop
          title="切换租户"
          name="iksvg_qiehuan-daohang"
        />
      </span>
      <span v-if="settingsStore.settings.navSearch.enable && tools?.search" class="item" @click="ikMitt.emit('global-search-toggle')">
        <IkSvgIcon
          :size="iconSize"
          pop
          title="搜索"
          name="iksvg_chaxun"
        />
      </span>
      <ElPopover
        v-if="settingsStore.settings.toolbar.enableNotification && tools?.notice"
        ref="refNews"
        trigger="click"
        :show-after="200"
        placement="bottom"
        :width="350"
      >
        <Notification ref="tabs" @close="handClosePopover" />
        <template #reference>
          <span class="item">
            <el-badge
              type="primary"
              :value="notifucationStore.total"
              :is-dot="notifucationStore.total > 99"
              :hidden="notifucationStore.total === 0"
            >
              <IkSvgIcon
                :size="iconSize"
                pop
                title="通知"
                padding="0"
                name="iksvg_xiaoxitongzhi"
              />
            </el-badge>
          </span>
        </template>
      </ElPopover>
      <IkI18nSelector v-if="tools?.i18n">
        <span class="item">
          <IkSvgIcon
            :size="iconSize"
            name="iksvg_zhongyingwen-daohang"
          />
        </span>
      </IkI18nSelector>
      <span
        v-if="settingsStore.mode === 'pc' && settingsStore.settings.toolbar.enableFullscreen && tools?.fullScreen"
        class="item"
        @click="toggle"
      >
        <IkSvgIcon
          :size="iconSize"
          pop
          :title="isFullscreen ? '退出全屏' : '全屏'"
          :name="isFullscreen ? 'iksvg_tuichuquanping' : 'iksvg_quanping'"
        />
      </span>
      <span v-if="settingsStore.settings.toolbar.enablePageReload && tools?.refresh" class="item" @click="mainPage.reload()">
        <IkSvgIcon
          pop
          :size="iconSize"
          title="刷新"
          name="iksvg_shuaxin2"
        />
      </span>
      <span
        v-if="settingsStore.settings.toolbar.enableColorScheme && tools?.theme"
        class="item"
        @click="toggleColorScheme"
      >
        <IkSvgIcon
          pop
          :title="isLight ? '夜间模式' : '日间模式'"
          :size="iconSize"
          :name="isLight ? 'iksvg_baitian' : 'iksvg_yejian'"
        />
      </span>
      <span
        v-if="settingsStore.settings.toolbar.enableAppSetting && tools?.setting"
        class="item"
        @click="ikMitt.emit('global-app-setting-toggle')"
      >
        <IkSvgIcon
          :size="iconSize"
          pop
          title="主题配置"
          name="iksvg_shezhi2"
        />
      </span>
    </div>
    <el-dropdown
      v-if="tools?.userInfo"
      class="user-container"
      size="default"
      @command="userCommand"
    >
      <div class="user-wrapper">
        <el-avatar shape="square" :size="28" :src="setFileUrl(userStore?.userInfo?.avatar)">
          <IkSvgIcon :size="iconSize" name="iksvg_jiaoseguanli" />
        </el-avatar>
        {{ userStore.account }}
        <IkSvgIcon :size="16" name="iksvg_zhankai-yemianbiaoqian" />
      </div>
      <template #dropdown>
        <el-dropdown-menu class="user-dropdown">
          <el-dropdown-item v-if="settingsStore.settings.home.enable" command="home">
            {{ generateI18nTitle('route.home', settingsStore.settings.home.title) }}
          </el-dropdown-item>
          <el-dropdown-item command="password">
            {{ t('app.modifyPassword') }}
          </el-dropdown-item>
          <!-- <el-dropdown-item command="setting">
              {{ t('app.profile') }}
            </el-dropdown-item> -->
          <el-dropdown-item v-if="settingsStore.mode === 'pc'" divided command="hotkeys">
            {{ t('app.hotkeys') }}
          </el-dropdown-item>
          <el-dropdown-item divided command="logout">
            {{ t('app.logout') }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<style lang="scss" scoped>
.tools {
  display: flex;
  align-items: center;
  padding-left: 20px;
  white-space: nowrap;

  :deep(.nav-org-picker){
    transition: top .35s;
    top: -50px;
    max-width: 200px;

    &.show{
      top: 0;
    }

    .el-input__wrapper{
      background-color: transparent !important;
      grid-column: 1;
    }
  }

  .buttons {
    margin-right: 20px;

    .item-switch{
      &:hover .el-icon{
        color: var(--el-color-primary);
      }
    }

    .item {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      height: 26px;
      width: 34px;
      cursor: pointer;
      vertical-align: middle;
      font-size: 18px;

      .el-icon {
        color: var(--ik-main-icon-deep-color);
        transition: var(--el-transition-color);
      }

      .el-badge {
        display: flex;
        align-items: center;
      }
    }
  }

  :deep(.language-container) {
    font-size: 16px;
  }

  :deep(.user-container) {
    display: inline-block;
    cursor: pointer;

    .user-wrapper {
      display: flex;
      align-items: center;

      .el-avatar {
        vertical-align: middle;
        margin-top: -2px;
        margin-right: 4px;
      }
    }
  }
}
</style>
